<script setup lang="ts">
/**
 * Main.vue —— ERP 主布局
 *
 * 结构：
 * - 左侧：二级菜单（Element Plus 的 el-menu / el-sub-menu + el-menu-item）
 * - 右侧：<RouterView /> 承载子页面（通过嵌套路由在 router/index.ts 中配置）
 *
 * 使用方式：
 * - 给 el-menu-item 的 index 一个“唯一键”（推荐与子路由 path 对齐，如 'ps-01' 或 'Ces'）
 * - 点击菜单时触发 handleSelect，将 index 组装为 /Main/{index} 并跳转
 * - 在 router/index.ts 的 Main.children 里新增对应 path 即可渲染到右侧
 *
 * 自定义：
 * - 想直接写完整路径，也支持：index="/Main/Ces"，handleSelect 会识别并原样跳转
 * - 想改菜单项数量或文案，直接在下方模板中增删 <el-menu-item> 即可
 */
import { RouterLink, RouterView } from 'vue-router'
// @ts-ignore
import HelloWorld from '../components/HelloWorld.vue'
// @ts-ignore
import {useCounterStore} from '@/stores/counter'
const store=useCounterStore();
import { useRouter,useRoute } from 'vue-router';
import { ref, computed, onMounted } from 'vue'
import { Box, Operation, Setting, DataLine, User, ShoppingCart, Tools, Timer, Monitor, Upload, Camera } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const router=useRouter()
const route=useRoute()
// 退出登录：清空 Pinia 用户信息与本地 token，并返回登录页
const closs=()=>{
  store.User.UserId=0
  store.User.UserName=''
  store.User.UserNickName=''
  store.User.RoleId=0
  store.User.RoleName=''
  store.User.Token=''
  localStorage.removeItem("token")
  router.push('/')
}

/**
 * 菜单点击回调
 * - index: 菜单项的唯一键。两种写法：
 *   1) 简洁键，如 'Ces'、'ps-01' → 自动拼为 '/Main/{index}'
 *   2) 完整路径，如 '/Main/Ces' 或 '/Ces' → 将按原路径跳转
 */
function handleSelect(index:string){
  // 排班管理模块路由映射
  if (index === 'scheduling/shift-list') {
    router.push('/Main/ShiftList')
  } else if (index === 'scheduling/team-list') {
    router.push('/Main/TeamList')
  } else if (index === 'scheduling/team-type-list') {
    router.push('/Main/TeamTypeList')
  } else if (index === 'scheduling/calendar-list') {
    router.push('/Main/CalendarList')
  } else if (index === 'scheduling/scheduli-list') {
    router.push('/Main/ScheduliList')
  } else if (index === 'scheduling/schedule-add') {
    router.push('/Main/ScheduleAdd')
  } else if (index === 'scheduling/weather') {
    router.push('/Main/Weather')
  } else if (index === 'scheduling/xunfei-chat') {
    router.push('/Main/XunfeiChat')
  }
  // 生产管理模块路由映射
  else if (index === 'produce-01') {
    router.push('/Main/ProductInfo')
  }
  else if (index === 'ProductDetail') {
    router.push('/Main/ProductDetail')
  }
  // 物料管理模块路由映射
  else if (index === 'quality-01') {
    router.push('/Main/MaterialInfo')
  }
  else if (index === 'MaterialDetail') {
    router.push('/Main/MaterialDetail')
  }
  // 工艺流程模块路由映射
  else if (index === 'device-01') {
    router.push('/Main/ProcessRouteInfo')
  } else if (index === 'device-02') {
    router.push('/Main/BomInfo')
  }
  else if (index === 'ProcessRouteDetail') {
    router.push('/Main/ProcessRouteDetail')
  }
  else if (index === 'BomDetail') {
    router.push('/Main/BomDetail')
  }
  // 系统管理模块（保持原有路由跳转）
  else if (index === 'Organize' || index === 'Post' || index === 'User' || index === 'Role' || index === 'Permission') {
    router.push(`/Main/${index}`)
  }
  // 库存管理模块
  else if (index === 'Inventoryreport') {
    router.push('/Main/Inventoryreport')
  }
  else if (index === 'TransferQuery') {
    router.push('/Main/TransferQuery')
  }
  else if (index === 'TransferAdd') {
    router.push('/Main/TransferAdd')
  }
  else if (index === 'TransferDetail') {
    router.push('/Main/TransferDetail')
  }
  else if (index === 'dify') {
    router.push('/Main/dify')
  }
  // 工具管理模块
  else if (index.startsWith('tool-')) {
    router.push(`/Main/${index}`)
  }
  // 数据看板模块
  else if (index.startsWith('board-')) {
    router.push(`/Main/${index}`)
  }
  // 客户供应商模块
  else if (index.startsWith('partner-')) {
    router.push(`/Main/${index}`)
  }
  // 采购销售管理模块
  else if (index.startsWith('ps-')) {
    router.push(`/Main/${index}`)
  }
  // 系统管理模块的其他项目
  else if (index === 'system-05') {
    router.push('/Main/system-05')
  }
  // 我的工单模块
  else if (index === 'DifyAi') {
    router.push('/Main/DifyAi')
  }
  // 客户供应商管理模块
  else if (index === '/Customerlist') {
    router.push('/Main/Customerlist')
  }
  else if (index === '/Supplierlist') {
    router.push('/Main/Supplierlist')
  }
  else if (index === '/proType') {
    router.push('/Main/proType')
  }
  else if (index === '/proShow') {
    router.push('/Main/proShow')
  }
  else if (index === '/proflowlist') {
    router.push('/Main/proflowlist')
  }
  else if (index === '/FlowAdd') {
    router.push('/Main/FlowAdd')
  }
  // 生产管理模块
  else if (index === '/Orderslist') {
    router.push('/Main/Orderslist')
  }
  else if (index === '/OrdersAdd') {
    router.push('/Main/OrdersAdd')
  }
  else if (index === '/OrderXiang') {
    router.push('/Main/OrderXiang')
  }
  else if (index === '/Dify') {
    router.push('/Main/Dify')
  }
  else if (index === '/Goodshow') {
    router.push('/Main/Goodshow')
  }
  // 采购销售管理模块
  else if (index === '/Verificationlist') {
    router.push('/Main/Verificationlist')
  }
  else if (index === '/Procurelist') {
    router.push('/Main/Procurelist')
  }
  else if (index === '/Contractlist') {
    router.push('/Main/Contractlist')
  }
  else if (index === '/Phraselist') {
    router.push('/Main/Phraselist')
  }
  // 其他模块暂时跳转到首页或显示提示
  else {
    console.log(`菜单项 ${index} 暂未配置路由`)
    // 可以根据需要跳转到默认页面或显示提示
    // router.push('/Main/ProductInfo') // 默认跳转到产品信息页面
  }
}

// 折叠菜单
const isCollapsed = ref(false)
const toggleCollapse = ()=>{ isCollapsed.value = !isCollapsed.value }

// 面包屑（简单从当前路由生成，可按需换成自定义映射）
const breadcrumb = computed(()=>{
  const path = route.path.replace(/^\/|\/$/g,'')
  return path.split('/')
})

// 头像相关
const userAvatar = ref('')
const avatarDialogVisible = ref(false)
const avatarPreview = ref('')
const avatarFile = ref<File | null>(null)

// 初始化头像
const initAvatar = () => {
  const savedAvatar = localStorage.getItem('userAvatar')
  if (savedAvatar) {
    userAvatar.value = savedAvatar
  }
}

// 处理头像上传
const handleAvatarUpload = (file: File) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarPreview.value = e.target?.result as string
    avatarFile.value = file
  }
  reader.readAsDataURL(file)
}

// 确认更换头像
const confirmAvatarChange = () => {
  if (avatarPreview.value) {
    userAvatar.value = avatarPreview.value
    localStorage.setItem('userAvatar', avatarPreview.value)
    avatarDialogVisible.value = false
    ElMessage.success('头像更换成功')
  }
}

// 取消更换头像
const cancelAvatarChange = () => {
  avatarPreview.value = ''
  avatarFile.value = null
  avatarDialogVisible.value = false
}

// 组件挂载时初始化头像
onMounted(() => {
  initAvatar()
})
</script>

<template>
  <!-- <header>
    <img alt="Vue logo" class="logo" src="@/assets/logo.svg" width="125" height="125" />

    <div class="wrapper">
      <HelloWorld msg="You did it!" />

      <nav>
        <el-tag type="success">用户名:{{store.User.UserName}},角色:{{store.User.RoleName}},昵称:{{store.User.UserNickName}}</el-tag>
        <RouterLink to="" @click="closs">退出登录</RouterLink>
       
      </nav>
    </div>
  </header> -->

  <!--
    布局容器
    - el-aside 放置在最左，固定宽度
    - el-main 占据右侧剩余空间，承载 RouterView 的业务页面
  -->
  <el-container class="erp-layout">
    <!-- 顶部彩色头部：系统名 / 面包屑 / 折叠菜单 / 用户与退出 -->
    <el-header class="erp-header">
      <div class="erp-header-left">
        <div class="erp-brand">ERP 管理系统</div>
      </div>
      <div class="erp-user">
        <el-button text circle @click="toggleCollapse" :title="isCollapsed ? '展开菜单' : '折叠菜单'">
          <el-icon><Operation /></el-icon>
        </el-button>
        
        <!-- 用户头像和姓名 -->
        <div class="user-info">
          <el-avatar 
            :size="36" 
            :src="userAvatar" 
            @click="avatarDialogVisible = true"
            class="user-avatar"
            :title="'点击更换头像'"
          >
            <el-icon><User /></el-icon>
          </el-avatar>
          <el-tag type="success" effect="dark" class="user-tag">
            <el-icon style="margin-right:4px"><User /></el-icon>{{store.User.UserNickName || store.User.UserName || '未登录'}}
          </el-tag>
        </div>
        
        <el-button type="danger" size="small" @click="closs">退出</el-button>
      </div>
    </el-header>
    <!-- 下方主容器：左侧菜单 + 右侧内容 -->
    <el-container class="erp-body">
      <!-- 左侧菜单：可折叠宽度 -->
      <el-aside :width="isCollapsed ? '66px' : '260px'" class="erp-aside">
        <el-scrollbar>
          <!-- 菜单：unique-opened 保证同级仅展开一个，default-active 指定默认高亮菜单项 -->
          <el-menu class="erp-menu" unique-opened :collapse="isCollapsed" @select="handleSelect" :default-active="'Inventoryreport'" >
            <!-- 每个一级模块包含 5 个二级功能项（无三级） -->
            <el-sub-menu index="warehouse">
              <template #title>
                <el-icon><Box /></el-icon>
                <span>管理</span>
              </template>
              <el-menu-item index="Inventoryreport">汇总表</el-menu-item>
              <el-menu-item index="TransferQuery">调拨管理</el-menu-item>
              <!-- <el-menu-item index="TransferAdd">调拨新增</el-menu-item>
              <el-menu-item index="TransferDetail">调拨详情</el-menu-item> -->
              <el-menu-item index="dify">智能客服</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="produce">
              <template #title>
                <el-icon><Monitor /></el-icon>
                <span>产品管理</span>
              </template>
              <el-menu-item index="produce-01">产品信息</el-menu-item>
              <el-menu-item index="ProductDetail">产品详情</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="quality">
              <template #title>
                <el-icon><DataLine /></el-icon>
                <span>物料管理</span>
              </template>
              <el-menu-item index="quality-01">物料信息</el-menu-item>
              <el-menu-item index="MaterialDetail">物料详情</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="device">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>Bom管理</span>
              </template>
              <el-menu-item index="device-01">工艺路线</el-menu-item>
              <el-menu-item index="ProcessRouteDetail">路线详情</el-menu-item>
              <el-menu-item index="device-02">Bom信息</el-menu-item>
              <el-menu-item index="BomDetail">Bom详情</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="tool">
              <template #title>
                <el-icon><Tools /></el-icon>
                <span>工具管理</span>
              </template>
              <el-menu-item index="tool-01">工具台账</el-menu-item>
              <el-menu-item index="tool-02">领用归还</el-menu-item>
              <el-menu-item index="tool-03">报废处理</el-menu-item>
              <el-menu-item index="tool-04">寿命统计</el-menu-item>
              <el-menu-item index="tool-05">工具报表</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="schedule">
              <template #title>
                <el-icon><Timer /></el-icon>
                <span>排班管理</span>
              </template>
              <el-menu-item index="scheduling/shift-list">班次列表</el-menu-item>
              <el-menu-item index="scheduling/team-list">团队列表</el-menu-item>
              <el-menu-item index="scheduling/team-type-list">团队类型</el-menu-item>
              <el-menu-item index="scheduling/calendar-list">日历排班</el-menu-item>
              <el-menu-item index="scheduling/scheduli-list">排班总览</el-menu-item>
              <el-menu-item index="scheduling/schedule-add">新增排班</el-menu-item>
              <el-menu-item index="scheduling/weather">天气查询</el-menu-item>
              <el-menu-item index="scheduling/xunfei-chat">讯飞助手</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="system">
              <template #title>
                <el-icon><Setting /></el-icon>
                <span>系统管理</span>
              </template>
              <el-menu-item index="Organize">组织管理</el-menu-item>
              <el-menu-item index="Post">岗位管理</el-menu-item>
              <el-menu-item index="User">用户管理</el-menu-item>
              <el-menu-item index="Role">角色管理</el-menu-item>
              <el-menu-item index="Permission">权限管理</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="board">
              <template #title>
                <el-icon><Monitor /></el-icon>
                <span>数据看板</span>
              </template>
              <el-menu-item index="board-01">生产看板</el-menu-item>
              <el-menu-item index="board-02">质量看板</el-menu-item>
              <el-menu-item index="board-03">仓储看板</el-menu-item>
              <el-menu-item index="board-04">设备看板</el-menu-item>
              <el-menu-item index="board-05">综合大屏</el-menu-item>
            </el-sub-menu>

            <el-sub-menu index="partner">
              <template #title>
                <el-icon><User /></el-icon>
                <span>客户供应商</span>
              </template>
              <el-menu-item index="/Customerlist">客户管理</el-menu-item>
              <el-menu-item index="/Supplierlist">供应商档案</el-menu-item>
               <el-menu-item index="/proType">工序管理分类</el-menu-item>
                <el-menu-item index="/proShow">工序管理</el-menu-item>
                 <el-menu-item index="/proflowlist">工艺流程</el-menu-item>
                  <el-menu-item index="/FlowAdd">工艺流程新增</el-menu-item>
            </el-sub-menu>
          
            

             <el-sub-menu index="workorder">
              <template #title>
                <el-icon><ShoppingCart /></el-icon>
                <span>生产管理</span>
              </template>
              <el-menu-item index="/Orderslist">生产工单</el-menu-item>
               <el-menu-item index="/OrdersAdd">新增生产工单</el-menu-item>
                <el-menu-item index="/OrderXiang">生产工单详情</el-menu-item>
            </el-sub-menu>

             <el-sub-menu index="ai">
              <template #title>
                <el-icon><Tools /></el-icon>
                <span>智能客服</span>
              </template>
              <el-menu-item index="/Dify">Dify智能客服</el-menu-item>
            </el-sub-menu>

             <el-sub-menu index="good">
              <template #title>
                <el-icon><ShoppingCart /></el-icon>
                <span>货品信息</span>
              </template>
              <el-menu-item index="/Goodshow">货品信息</el-menu-item>
            </el-sub-menu>


            <el-sub-menu index="purchase-sale">
              <template #title>
                <el-icon><ShoppingCart /></el-icon>
                <span>采购销售管理</span>
              </template>
              <el-menu-item index="/Verificationlist">采购核价</el-menu-item>
              <el-menu-item index="/Procurelist">采购单</el-menu-item>
              <el-menu-item index="/Contractlist">采购合同</el-menu-item>
              <el-menu-item index="/Phraselist">销售合同</el-menu-item>

            </el-sub-menu>

            <el-sub-menu index="workorder">
              <template #title>
                <el-icon><Box /></el-icon>
                <span>我的工单</span>
              </template>
              <el-menu-item index="DifyAi">智能客服</el-menu-item>
            </el-sub-menu>

          </el-menu>


          
        </el-scrollbar>
      </el-aside>
       <!-- 右侧业务内容：由嵌套路由渲染在此处 -->
      <el-main class="erp-main">
        <RouterView />
      </el-main>
    </el-container>
    
    <!-- 头像更换对话框 -->
    <el-dialog
      v-model="avatarDialogVisible"
      title="更换头像"
      width="400px"
      :before-close="cancelAvatarChange"
    >
      <div class="avatar-upload-container">
        <!-- 当前头像预览 -->
        <div class="current-avatar">
          <h4>当前头像</h4>
          <el-avatar :size="80" :src="userAvatar">
            <el-icon><User /></el-icon>
          </el-avatar>
        </div>
        
        <!-- 新头像预览 -->
        <div class="new-avatar" v-if="avatarPreview">
          <h4>新头像预览</h4>
          <el-avatar :size="80" :src="avatarPreview">
            <el-icon><User /></el-icon>
          </el-avatar>
        </div>
        
        <!-- 文件上传 -->
        <div class="upload-section">
          <el-upload
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
            @change="(file: any) => handleAvatarUpload(file.raw)"
          >
            <el-button type="primary" :icon="Camera">
              选择头像
            </el-button>
          </el-upload>
          <p class="upload-tip">支持 JPG、PNG 格式，建议尺寸 200x200 像素</p>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAvatarChange">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmAvatarChange"
            :disabled="!avatarPreview"
          >
            确认更换
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>

<style scoped>
/* 说明：以下样式仅作用于本页面，确保菜单贴左、内容填满右侧 */
header {
  line-height: 1.5;
  max-height: 100vh;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0 16px;
}

.user-avatar {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.user-avatar:hover {
  border-color: #409eff;
  transform: scale(1.1);
}

.user-tag {
  margin: 0;
}

/* 头像上传对话框样式 */
.avatar-upload-container {
  text-align: center;
}

.current-avatar,
.new-avatar {
  margin-bottom: 20px;
}

.current-avatar h4,
.new-avatar h4 {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.upload-section {
  margin-top: 20px;
}

.upload-tip {
  margin: 8px 0 0 0;
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}

.logo {
  display: block;
  margin: 0 auto 2rem;
}

nav {
  width: 100%;
  font-size: 12px;
  text-align: center;
  margin-top: 2rem;
}

nav a.router-link-exact-active {
  color: var(--color-text);
}

nav a.router-link-exact-active:hover {
  background-color: transparent;
}

nav a {
  display: inline-block;
  padding: 0 1rem;
  border-left: 1px solid var(--color-border);
}

nav a:first-of-type {
  border: 0;
}

@media (min-width: 1024px) {
  header {
    display: flex;
    place-items: center;
    padding-right: calc(var(--section-gap) / 2);
  }

  .logo {
    margin: 0 2rem 0 0;
  }

  header .wrapper {
    display: flex;
    place-items: flex-start;
    flex-wrap: wrap;
  }

  nav {
    text-align: left;
    margin-left: -1rem;
    font-size: 1rem;

    padding: 1rem 0;
    margin-top: 1rem;
  }
}
</style>
<style>
/* 解除 Vite 模板对 #app 的居中与最大宽度限制，铺满全屏 */
#app{
  max-width: 100% !important;
  margin: 0 !important;
  padding: 0 !important;
}
html,body{
  height: 100%;
  background: #fff;
}
.erp-layout{
  height: 100vh; /* 让容器充满可视高度 */
  width: 100vw;  /* 铺满浏览器宽度 */
  background: #fff;
}
.erp-body{
  height: calc(100vh - 56px); /* 扣除头部高度 */
  width: 100vw;              /* 与浏览器同宽 */
  background: #fff;
}
.erp-header{
  background: linear-gradient(90deg,#1556F0 0%, #49A5FF 100%);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  height: 56px;
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  width: 100vw; /* 与浏览器等宽 */
  z-index: 10;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.erp-header-left{ display:flex; align-items:center; gap:16px; }
.erp-breadcrumb :deep(.el-breadcrumb__item){ color:#eaf1ff; }
.erp-breadcrumb :deep(.el-breadcrumb__inner){ color:#eaf1ff; }
.erp-brand{
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 1px;
}
.erp-user{ display:flex; align-items:center; gap:8px; }
.erp-aside{
  border-right:1px solid var(--color-border); /* 左侧描边 */
}
.erp-menu{
  border-right:1px solid var(--color-border);
  --el-menu-active-color: #1556F0;
  --el-menu-hover-bg-color: rgba(21,86,240,0.06);
  --el-color-primary: #1556F0;
  padding: 8px 0;
}
.erp-main{
  padding: 12px;   /* 右侧内容区内边距 */
  overflow: auto;  /* 内容超出时滚动 */
  background: #fff;
}
</style>
